package sample.pages;

import org.dreamwork.jasmine2.engine.DownloadManager;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.events.IClickListener;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.web.controls.Button;
import org.dreamwork.jasmine2.web.controls.FileControl;
import org.dreamwork.jasmine2.web.controls.Literal;
import org.dreamwork.jasmine2.web.controls.Page;
import org.dreamwork.jasmine2.web.html.GenericHtmlControl;
import org.dreamwork.util.VirtualFile;
import sample.data.DataItem;

import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 11-11-28
 * Time: 上午11:16
 */
public class TestPage extends Page {
    protected FileControl file1;
    protected Button button;
    protected GenericHtmlControl div;

    protected DataItem item;
    protected boolean success = true;

    protected java.util.List<DataItem> list = java.util.Arrays.asList (
            new DataItem ("item1", "Name 1"), new DataItem ("item2", "Name 2")
    );

    public TestPage () {
        item = new DataItem ("seth.yang", "seth.yang");
    }

    @Override
    public void onPagePreload (Page page) throws EventException {
        button.addClickListener (new IClickListener() {
            public void onClick (IWebControl sender) throws EventException {
                save ();
            }
        });
    }

    @Override
    public void onPageLoadCompleted (org.dreamwork.jasmine2.web.controls.Page page) throws org.dreamwork.jasmine2.events.EventException {
        try {
            dataBind ();
        } catch (Throwable throwable) {
            throwable.printStackTrace ();
        }
    }

    private void save () {
        VirtualFile vf = file1.getVirtualFile ();
        try {
            DownloadManager.save (vf, null);
            String name = vf.getName ();
            StringBuilder builder = new StringBuilder ();
            builder.append ("<a href='").append (request.getContextPath ()).append ("/downloads/")
                    .append (DownloadManager.encode (name)).append ("'> download file </a>");
            div.addControl (new Literal (builder));
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}
